package com.yjd.comm.system.util;

import java.util.List;
import java.util.Map;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.device.model.DevicePushModel;
import com.yjd.comm.device.model.PushRecordModel;
import com.yjd.comm.device.model.PushTaskModel;
import com.yjd.comm.device.model.UserDeviceModel;
import com.yjd.comm.device.service.IDevicePushService;
import com.yjd.comm.device.service.IPushRecordService;
import com.yjd.comm.device.service.IUserDeviceService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServiceHolder;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.vo.Constant.SysParamKeyEnum;

public class PushUtil {
	private static JPushClient client;
	
	public static JPushClient getPushClient() throws Exception {
		if (client == null) {
			client = new JPushClient(SysParamUtil.getValue(
					SysParamKeyEnum.PUSH_APP_SECRET).trim(), SysParamUtil
					.getValue(SysParamKeyEnum.PUSH_APP_KEY).trim());
		}
		return client;
	}

	private static IUserDeviceService getUserDeviceService() {
		return ServiceHolder.getService(IUserDeviceService.class,
				"userDeviceService");
	}

	private static IDevicePushService getDevicePushService() {
		return ServiceHolder.getService(IDevicePushService.class,
				"devicePushService");
	}

	private static IPushRecordService getPushRecordService() {
		return ServiceHolder.getService(IPushRecordService.class,
				"pushRecordService");
	}
	
	
	/**
	 * 
	 * 添加部分设备推送任务
	 * 
	 * @param list 推送内容任务
	 * @throws Exception
	 */
	public static void addPushTask(List<PushTaskModel> list) throws Exception {
		for (PushTaskModel model : list) {
			if (model.getUserId() != null) {
				UserDeviceModel udc = getUserDeviceService()
						.getUserDeviceModelByUser(model.getUserId());
				if (udc != null) {
					DevicePushModel content = insertContentModel(
							model.getContent(), model.getExtra(), 2);
					PushRecordModel task = new PushRecordModel();
					task.setAddtime(FrameUtil.getTime(null));
					task.setUptime(FrameUtil.getTime(null));
					task.setDevice_id(udc.getDevice_id());
					task.setContent_id(content.getContent_id());
					task.setIs_push(0);
					task.setPush_times(0);
					getPushRecordService().insert(task);
				}
			}
		}
	}

	
	@SuppressWarnings("rawtypes")
	private static DevicePushModel insertContentModel(String content, Map map,
			Integer target) throws Exception {
		DevicePushModel contents = new DevicePushModel();
		contents.setContent(content);
		contents.setExtras(JSON.toJSONString(map));
		contents.setTarget(target);
		contents = getDevicePushService().insert(contents);
		return contents;
	}

	/**
	 * 
	* 添加全部设备推送任务
	* @param content
	* @param map
	* @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static void addPushAllTask(String content, Map map) throws Exception {
		if (StringUtil.isNotEmpty(content)) {
			getPushClient();
			DevicePushModel contents = insertContentModel(content, map, 1);
			PushRecordModel task = new PushRecordModel();
			task.setContent_id(contents.getContent_id());
			task.setIs_push(0);
			task.setPush_times(0);
			task.setAddtime(FrameUtil.getTime(null));
			task.setUptime(FrameUtil.getTime(null));
			getPushRecordService().insert(task);
		}
	}

	/**
	 * 
	 * 获取regId s格式:yjd_设备regid_android|ios
	 * 
	 * @param s
	 * @return
	 */
	public static String getRegistrationId(String s) {
		if (StringUtil.isNotEmpty(s)) {
			String[] strings = s.split("_");
			if (strings.length > 1)
				s = strings[1];
		}
		return s;
	}

	/**
	 * 
	* 无记录发送推送（测试）
	* @param content
	* @return
	* @throws Exception
	 */
	@SuppressWarnings("unused")
	private static PushResult pushAll(String content) throws Exception{
		PushResult result=null;
		if(StringUtil.isNotEmpty(content)){
			getPushClient();
			result=client.sendNotificationAll(content);
		}
		return result;
	}
	
	/**
	 * 
	 * 无记录发送推送（测试）
	 * 
	 * @param registrationID
	 *            推送设备regId
	 * @param content
	 *            推送内容
	 * @param extras
	 *            附加属性
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	private static PushResult pushList(String[] registrationID, String content,
			Map extras) throws Exception {
		getPushClient();
		return client.sendPush(PushPayload
				.newBuilder()
				.setPlatform(Platform.all())
				.setAudience(Audience.registrationId(registrationID))
				.setNotification(Notification.alert(content))
				.setMessage(
						Message.newBuilder().setMsgContent(content)
								.addExtras(extras).build()).build());
	}
}
